<?php

require_once( dirname(__FILE__).'/../libs/bedmintonlib.php' );

if (! isset( $_GET[ 'optimizeDatabase' ] ))
    exit;

if ($_GET[ 'optimizeDatabase' ] != "martinoptimizuje")
    exit;

$db = Db::db();
$dbConnection = $db->connectionNoTransaction();
if (is_null( $dbConnection ))
{
    logError( "Cron:" . $db->getErrorStr() );
    return;
}

try
{
    $statement = $dbConnection->prepare( "VACUUM FULL ANALYZE" );
    $statement->execute();
    $statement = $dbConnection->prepare( "SELECT imagepreviewpath, imagepath FROM galleryimages");
    $statement->execute();
    $result = $statement->fetchAll( PDO::FETCH_NUM );
    if (! $result)
        return; 
}
catch (PDOException $e)
{
    logError( "Cron: " . $e->getMessage() );
    return;
}

// aby sa dalo searchovat na nulovu hodnotu
$j = 0;
$allImages[ $j ] = "xx";
$j ++;

for ($i = 0; $i < count( $result ); $i ++)
{
    $allImages[ $j ] = $result[ $i ][ 0 ];
    $j ++;
    $allImages[ $j ] = $result[ $i ][ 1 ];
    $j ++;
}

$dirPath = $_SERVER[ 'DOCUMENT_ROOT' ] . '/galleryimages';
$handle = opendir( $dirPath );
if (! $handle)
{
   logError( "Cron: Unable to open directory" );
   return;
}
   
while (false !== ($entry = readdir($handle))) 
{
    if ($entry != "." && $entry != "..") 
    {
        $key = array_search( $entry, $allImages );
        if ($key > 0)
        {
            unset( $allImages[ $key ] );
        }
        else 
        {
            $filePath = $dirPath . "/" . $entry;
            unlink( $filePath );
        }
    }
}

closedir( $handle );
for ($i = 1; $i < count( $allImages ); $i ++)
{
    try
    {
        $statement = $dbConnection->prepare( "DELETE FROM galleryimages WHERE imagepreviewpath = ? OR imagepath = ?" );
        $statement->bindParam( 1, $allImages[ $i ], PDO::PARAM_STR );
        $statement->bindParam( 2, $allImages[ $i ], PDO::PARAM_STR );
        $statement->execute();
    }
    catch (PDOException $e)
    {
        logError( "Cron: " . $e->getMessage() );
        return;
    }
}

?>
